package dc.connectionmanager.database;

import java.sql.*;
import java.util.ArrayList;

import dc.connectionmanager.persistance.AConnection;

public abstract class  DBConnection extends AConnection implements IDBConnection
{
	protected int port;
	protected String databaseName;
	protected Connection conn;
	
	public DBConnection(String nIPAdress, int nPort, String nUsername, String nPassword, String nDatabaseName) 
	{
		super(nIPAdress, nUsername, nPassword);
		this.port = nPort;
		this.databaseName = nDatabaseName;
	}
	
	@Override
	public boolean connect() 
	{
		try
		{
			this.initConnectionDriver();
			return this.isConnected();
		}
		catch(Exception ex)
		{
			System.out.println(ex.getMessage());
			return false;
		}
		finally
		{ }
	}

	@Override
	public boolean isConnected() 
	{
		try 
		{
			return !this.conn.isClosed();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			return false;
		}
		finally
		{}
	}

	@Override
	public void closeConnection() 
	{
		try 
		{
			this.conn.close();
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
		finally
		{
			this.conn = null;
		}
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object sendCommand(String command) 
	{
		ResultSet rset = null;
		Statement stmt = null;
		ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
		
		try 
	    {
		   stmt = conn.createStatement();
		   rset = stmt.executeQuery(command);
		   int n = rset.getMetaData().getColumnCount();
		   
		   ArrayList<String> tmp = new ArrayList<String>();
		   
		   for(int i = 1; i <= n; ++i)
		   {
			   tmp.add(rset.getMetaData().getColumnName(i));
		   }
		   ret.add((ArrayList<String>) tmp.clone());
		   tmp.clear();
		   
		   while(rset.next())
		   {
			   for(int i = 1; i <= n; ++i)
			   {
				   tmp.add(rset.getString(i));
			   }
			   ret.add((ArrayList<String>) tmp.clone());
			   tmp.clear();
		   }
		   
		   tmp = null;
           return ret.clone();

	   }
	   catch(Exception ex)
	   {
		   System.out.println(ex.getMessage());
		   //ex.printStackTrace();
		   return null;
	   }
	   finally
	   {
		   try 
		   {
			   rset.close();
			   stmt.close();
			   rset = null;
			   stmt = null;
			} 
		   catch (Exception ex) 
		   {
			   //Nothing to do here
				//ex.printStackTrace();
		   }
	   }
	}

	@Override
	public void sendCommandNC(String command) 
	{
		try 
	    {
		   conn.createStatement().executeUpdate(command);
	    }
	    catch(Exception ex)
	    {
	    	System.out.println(ex.getMessage());
	    	//ex.printStackTrace();
	    }
	   finally
	   { }
	}

}
